package com.wmc.controller;

import com.wmc.pojo.PageResult;
import com.wmc.pojo.Result;
import com.wmc.pojo.Student;
import com.wmc.pojo.StudentQueryParam;
import com.wmc.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping("/students")
@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result page(StudentQueryParam studentQueryParam) {
        log.info("分页查询学生信息，参数：{}", studentQueryParam);
        PageResult<Student> pageResult =studentService.page(studentQueryParam);
        return Result.success(pageResult);
    }

    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("保存学生信息，参数：{}", student);
        studentService.save(student);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询学生信息，参数：{}", id);
        Student student = studentService.getById(id);
        return Result.success(student);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        log.info("更新学生信息，参数：{}", student);
        studentService.update(student);
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除学生信息，参数：{}", id);
        studentService.deleteById(id);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result updateViolation(@PathVariable Integer id, @PathVariable Short score) {
        log.info("更新学生信息，参数：{}", id);
        Student student = studentService.getById(id);
        if (student == null) {
            return Result.error("学生不存在");
        }
        student.setViolationScore(score);
        student.setViolationCount((short) (student.getViolationCount() + 1));
        studentService.updateScore(student);
        return Result.success();
    }

}
